package kr.hkit.androidcomplete02.ch16;

import kr.hyunist.androidcomplete01.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class DlgQuestionFrgEx extends Activity implements QuestionDialgFragment.NoticeDialogListener {
	TextView tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch16_dialog);

		tv = (TextView) findViewById(R.id.ch16_text);
	}

	public void mOnClick(View v) {
		QuestionDialgFragment qFrg = new QuestionDialgFragment();
		Bundle bundle = new Bundle();
		bundle.putString("title", "질문");
		bundle.putString("msg", "어떤 연산할래?");
		bundle.putString("Q1", "덧셈");
		bundle.putString("Q2", "곱셈");
		bundle.putInt("a", 3);
		bundle.putInt("b", 4);

		qFrg.setArguments(bundle);

		qFrg.show(getFragmentManager(), "dialog");
	}

	@Override
	public void onDialogClick(DialogFragment dialog, int res) {
		tv.setText("결과 값 : " + res);
	}

}

class QuestionDialgFragment extends DialogFragment {
	NoticeDialogListener mListener;
	Bundle bundle;

	// Fragment에서 Activity에게 값전달 기법
	public interface NoticeDialogListener {
		public void onDialogClick(DialogFragment dialog, int res);
	}

	@Override
	public void onAttach(Activity activity) {
		Log.d("DlgQuestionFrgEx", "QuestionDialgFragment - onAttach()");
		super.onAttach(activity);
		try {
			mListener = (NoticeDialogListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ "NoticeDialogListene을 구현해야 됨");
		}
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		bundle = getArguments();
		return new AlertDialog.Builder(getActivity())
				.setTitle(bundle.getString("title"))
				.setIcon(R.drawable.ic_launcher)
				.setMessage(bundle.getString("msg"))
				.setPositiveButton(bundle.getString("Q1"), listener)
				.setNegativeButton(bundle.getString("Q2"), listener).create();
	}

	OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			int a = bundle.getInt("a");
			int b = bundle.getInt("b");
			switch (which) {
			case DialogInterface.BUTTON_POSITIVE:
				mListener.onDialogClick(QuestionDialgFragment.this, a + b);
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				mListener.onDialogClick(QuestionDialgFragment.this, a * b);
				break;
			}

		}
	};
}